#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#


from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api import urlfetch


import logging
import httplib,urllib,urlparse
import simplejson as json
import base64


class SchemeException(Exception):
    pass


class MainHandler(webapp.RequestHandler):

    def __init__(self):
        self._parsed_params = None 

    def get(self):
        self.post()

    def post(self):

        data = self._do_request()
        
        output = self._outputResult(data) 

        self.response.out.write(output)

    def _do_request(self):

        url      = self._inputParam('url')
        method   = self._inputParam('method')
        headers  = self._inputParam('headers')
        postdata = self._inputParam('postdata')

        # logging.info(headers)
        
        response_status = 500
        response_headers = []
        response_body = ''

        logging.info("%s %s", method, url)

        try:
            up = urlparse.urlparse(url)
    
            path = up.path
            if up.query != '':
                path += '?' + up.query

            if up.scheme == 'https':
                conn = httplib.HTTPSConnection(up.netloc)
            elif up.scheme == 'http':
                conn = httplib.HTTPConnection(up.netloc)
            else:
                raise SchemeException 

            conn.request(method, path, postdata, headers)
            response = conn.getresponse()

            response_status = response.status
            response_headers = response.getheaders()
            response_body = response.read()
            conn.close()
        except urlfetch.DownloadError:
            response_headers.append(('Content-Type', 'text/plain'))
            response_body = "Error Download"
        except SchemeException:
            response_headers.append(('Content-Type', 'text/plain'))
            response_body = "Error Scheme"
            
        return {'status':response_status, 'headers':response_headers, 'body':response_body}


    def _inputParam(self, name):
        """
        if not self._parsed_params:
            self._parsed_params = self.request.headers

        return self._parsed_params.get(name)
        """
        if name == 'headers':
            headers = {}
            for name in self.request.arguments():
                if name[:7] == 'header-':
                    n = name[7:]
                    n = self._cap_header_key(n)
                    v = self.request.get(name)
                    v = self._decode(v)
                    headers[n] = v
            return headers
        else:
            v = self.request.get('qroxy-' + name)
            v = self._decode(v)
            return v

    def _decode(self, value):
        return base64.b64decode(value)

    def _outputResult(self, data):
        data['body'] = base64.b64encode(data['body'])
        return json.dumps(data)

    def _cap_header_key(self, key):
        return '-'.join((ck.capitalize() for ck in key.split('-')))
 

def main():
    application = webapp.WSGIApplication([('/p', MainHandler)],
                                       debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
